package com.yq.tanhua.ui.login.viewmodel

import androidx.lifecycle.viewModelScope
import com.fmt.mvi.learn.gobal.log
import com.google.gson.Gson
import com.hyphenate.EMCallBack
import com.yq.tanhua.net.BaseViewModel
import com.yq.tanhua.net.TanHuaApiService
import com.yq.tanhua.ui.USER_TOKEN
import com.yq.tanhua.im.ImFunction
import com.yq.tanhua.ui.login.LoginViewAction
import com.yq.tanhua.ui.login.LoginViewState
import com.yq.tanhua.utils.UserCenter
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import mmkv.SpUtils
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import javax.inject.Inject


/**
 * @author: user
 * @date: 2023/2/28
 */
@HiltViewModel
class LoginViewModel @Inject constructor() : BaseViewModel() {
    @Inject
    lateinit var imFunction: ImFunction

    sealed class LoginViewEvent {
        class ShowVerifyFail(var msg: String) : LoginViewEvent()
    }


    private val _viewState = MutableStateFlow<LoginViewState?>(null)
    val state: StateFlow<LoginViewState?> = _viewState

    private val _viewEvent = MutableSharedFlow<LoginViewEvent?>()
    val viewEvent = _viewEvent.asSharedFlow()

    //用户行为
    val userIntent = MutableSharedFlow<LoginViewAction>()

    init {
        viewModelScope.launch {
            "哈哈哈哈".log()
            userIntent.collect {
                when (it) {
                    is LoginViewAction.SendMsgCode -> {
                        getPhoneCode(it.phone)
                    }

                    is LoginViewAction.VerifyMsgCode -> {
                        verifyPhoneCode(it.phone, it.code)
                    }
                }
            }
            "哈哈哈哈 执行不到吗".log()
        }


    }

    private fun getPhoneCode(phone: String) {
        _viewState.value = LoginViewState.Loading
        launch(
            block = {
                val map: HashMap<String, Any> = HashMap()
                map.put("phone", phone)
                val jsonParam = Gson().toJson(map)
                val body =
                    jsonParam.toRequestBody("application/json;charset=utf-8".toMediaType())
                val fullData = TanHuaApiService.sendMsg(body).fullData()
                fullData.log()
                _viewState.value = LoginViewState.Success
            }, error = {
                it.log()
                _viewState.value = LoginViewState.Fail
            })
    }

    private fun verifyPhoneCode(phone: String, code: String) {
        launch(
            block = {
                val map: HashMap<String, Any> = HashMap()
                map.put("phone", phone)
                map.put("verificationCode", code)
                val jsonParam = Gson().toJson(map)
                val body =
                    jsonParam.toRequestBody("application/json;charset=utf-8".toMediaType())
                val fullData = TanHuaApiService.loginVerification(body).fullData()
                SpUtils.put(USER_TOKEN, fullData.token)

                val hxInfoJSON = JSONObject(TanHuaApiService.getHxInfo())
                val hxId = hxInfoJSON.getString("username");
                val hxPwd = hxInfoJSON.getString("password")
                imFunction.loginOut()
                imFunction.login(hxId, hxPwd, object : EMCallBack {
                    // 登录成功回调
                    override fun onSuccess() {
                        _viewState.value = LoginViewState.VerifySucess(fullData.isNew)

                        viewModelScope.launch {
                            val userInfo = TanHuaApiService.getUserInfo().fullData()
                            userInfo.hxPwd = hxPwd
                            userInfo.hxId = hxId
                            UserCenter.updateUserInfo(userInfo)
                        }


                    }

                    // 登录失败回调，包含错误信息
                    override fun onError(code: Int, error: String) {
                        viewModelScope.launch {
                            _viewEvent.emit(LoginViewEvent.ShowVerifyFail("im 登录失败:  $error"))
                        }
                    }
                })


            }, error = {
                it.log()
                _viewEvent.emit(LoginViewEvent.ShowVerifyFail(it.message))
            })
    }
}